import random
from xml.dom import ValidationErr

from django.core.cache import caches
from django.core.validators import EmailValidator

from apps.UserManagement.task import send_verification_email_task


def validater_email(email):
    validater = EmailValidator()
    try:
        validater(email)
        return True
    except ValidationErr:
        return False


# 发送验证码邮件并缓存验证码
class EmailVerificationUtils:
    @staticmethod
    def generate_verification_code():
        """
        生成一个6位数的验证码
        """
        return str(random.randint(100000, 999999))

    @staticmethod
    def cache_verification_code(key, verification_code, timeout=300):
        """
        将验证码缓存到 Redis，设置过期时间为timeout秒（默认5分钟）
        """
        caches["sms"].set(key, verification_code, timeout)

